package cn.easybuy.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.easybuy.util.DBUtil;

public class BaseDao {

	protected Connection connection = null;
	protected PreparedStatement pstmt = null;

	// 关闭公共操作
	public void closeAll(Connection connection, PreparedStatement pstmt,
			ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if (pstmt != null) {
				pstmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	// 增 删 改 公共部分
	public int executeUpdate(String sql, Object... params) {
		int num = 0;
		try {
			connection = DBUtil.getConnection();
			pstmt = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
			num = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(connection, pstmt, null);
		}
		return num;
	}

	// 查询的公共部分
	public ResultSet exxcuteQuery(String sql, Object... params) {
		ResultSet rs = null;
		try {
			connection = DBUtil.getConnection();
			pstmt = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
}
